
#include <stdint.h>
#include <string.h>

#include "USB_HID.h"
#include "HIDKeyboard.h"

#include "Util.h"

#define INVALID_CODE		0x27

/*-----------------------------------------------------------*/


static void Keyboard_ReportBuf(uint8_t buf[], uint32_t len){
	uint32_t i;

	for(i = 0; i < len; i++){
		HID_KB_SendKey(buf[i]);
		WatchDog_Reset();
	}
}

void Keyboard_ReportRaw(uint8_t val[], uint32_t len){
	Keyboard_ReportBuf(val, len);
	HID_KB_Enter();
}

void Keyboard_ReportHex(uint8_t val[], uint32_t len){
	uint32_t i;
	
	for(i = 0; i < len; i++){
		HID_KB_SendKey(ValueToHexCode(val[i] >> 4));
		HID_KB_SendKey(ValueToHexCode(val[i] & 0x0F));
		WatchDog_Reset();
	}
	HID_KB_Enter();
}

void Keyboard_ReportBCD(uint8_t val[], uint32_t len){
	uint32_t i;
	
	for(i = 0; i < len; i++){
		HID_KB_SendKey(ValueToDecCode(val[i] >> 4));
		HID_KB_SendKey(ValueToDecCode(val[i] & 0x0F));
		WatchDog_Reset();
	}
	HID_KB_Enter();
}


void Keyboard_ReportDec(uint64_t v, uint8_t width){
	uint8_t code[32];
	uint32_t i;
	memset(code,0, sizeof(code));
	i = 0;
	do{
		code[i++] = v % 10;
		v /= 10;
	}while(v);
	if(i < width){
		i = width;
	}
	for(; i > 0; ){
		HID_KB_SendKey(ValueToDecCode(code[--i]));
	}
	HID_KB_Enter();
}


void HIDKeyboard_Report(uint8_t lsb, uint8_t format, uint8_t val[], uint32_t len){
	switch(format){
	case REP_FRM_HEX: Keyboard_ReportHex(val, len); break;
	case REP_FRM_BCD: Keyboard_ReportBCD(val, len); break;
	case REP_FRM_RAW: Keyboard_ReportRaw(val, len); break;
	case REP_FRM_DEC:
	default:{
		Keyboard_ReportDec(BufToValue(lsb, val, len), len * 2 + 2); break;
	}
	}
}



#if 0
void HIDKeyboard_SendSeqNum(uint8_t hid_format, SeqNum* seq){
	switch(hid_format){
	case REP_FRM_HEX: Keyboard_ReportHex(seq->sn, seq->length); break;
	case REP_FRM_BCD: Keyboard_ReportBCD(seq->sn, seq->length); break;
	case REP_FRM_RAW: Keyboard_ReportRaw(seq->sn, seq->length); break;
	case REP_FRM_DEC:
	default:{
		Keyboard_ReportDec(BufToValue(seq->lsb, seq->sn, seq->length)); 
		break;
	}
	}
}
#endif 


